<template>
  <div class="quickreplay_custom_edit_box">
    <!-- 编辑快捷回复或分类 -->
    <div class="quickreplay_custom_edit" v-if="!changeSortFlag">
      <div v-if="todoType === 'list'" class="title">
        当前分类: {{currentCategoryName}}
      </div>
      <div class="title">温馨提示：通过拖动前方的图标，快速设定工具栏标签的顺序位置，增加或编辑的时候不可拖拽</div>
      <el-form :model="editData" ref="editData" class="quick_reply_dialog">
        <!--快捷回复 || 分类-->
        <draggable :list="editData.data" :options="{handle:'.handle'}" @start="drag=true" @end="drag=false">
          <el-form-item
                  v-for="(domain, index) in editData.data"
                  class="quickreply_li"
                  :prop="'data.' + index + '.content'">
            <!-- 快捷回复列表 -->
            <span class="iconfont icon-shunxutuozhuai" v-show="editindex !== -1 && editindex !== index"></span>
            <span class="handle iconfont icon-shunxutuozhuai" v-show="editindex === -1 && editindex !== index"></span>
            <span class="ellipsis content_span" @click.stop="changeEditIndex(index)" v-show="editindex !== index">{{domain.content}}</span>
            <span class="span_btn span_btn_delete color color1" type="text" size="mini" @click.prevent="removeDomain(domain)" v-show="editindex !== index">删除</span>
            <!-- 编辑快捷回复 || 分类 -->
            <el-input
                    v-show="editindex === index"
                    class="quickreplay_custom_edit_input"
                    type="textarea"
                    :autosize="true"
                    resize="none"
                    size="mini"
                    placeholder="请输入内容"
                    v-model="textarea.content">
            </el-input>
            <!--<textarea type="text" v-show="editindex === index" class="quickreplay_custom_edit_input" v-model="domain.content"/>-->
            <div class="todo_box" v-show="editindex === index">
              <span class="iconfont icon-xuanzhong" @click="saveEdit(domain, 'edit')"></span>
              <span class="iconfont icon-qiapianshangdeguanbi" @click="cancelEdit(domain, 'edit')"></span>
            </div>
          </el-form-item>
        </draggable>
        <!-- 添加快捷回复 -->
        <div class="add_box" v-show="addData.length">
          <div v-for="(item, index) in addData" class="add_box_textarea">
            <el-input
                    class="quickreplay_custom_edit_input"
                    type="textarea"
                    :autosize="true"
                    resize="none"
                    placeholder="请输入内容"
                    v-model="item.content">
            </el-input>
            <!--<textarea type="text" class="quickreplay_custom_edit_input" v-model="item.content"/>-->
            <div class="todo_box">
              <span class="iconfont icon-xuanzhong" @click="saveEdit(item, 'add', index)"></span>
              <span class="iconfont icon-qiapianshangdeguanbi" @click="cancelEdit(item, 'add', index)"></span>
            </div>
          </div>
        </div>
        <!-- 添加快捷回复按钮 -->
        <div class="add-btn">
          <el-button @click.stop="addDomain" size="mini" class="color el-icon-plus color2">{{btnTitle}}</el-button>
        </div>
        <!-- 保存快捷回复 -->
        <div class="button_box">
          <el-button class="primary_btn" @click="cancel" size="small">{{$t('public.cancel')}}</el-button>
          <el-button class="primary_btn" @click.stop="custQkReSubmit" type="primary" size="small">{{$t('public.save')}}</el-button>
        </div>
      </el-form>
    </div>
    <!-- 变更分类 -->
    <el-form :model="moveSort" ref="moveSort" :rules="sortRules" class="quickreplay_sort_edit" v-if="changeSortFlag">
      <!-- 列表 -->
      <el-form-item prop="checkedReply" class="chang-quickreply-sort">
        <el-checkbox-group v-model="moveSort.checkedReply">
          <el-checkbox class="check_box_li" v-for="obj in editData.data" :label="obj._id" name="checkedReply" :key="obj._id">{{obj.content}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 分类下拉框 -->
      <el-form-item :label="$t('webchat.moveTo')" prop="categoryId">
        <el-select v-model="moveSort.categoryId" placeholder="请选择">
          <el-option
                  v-for="(item,index) in sort"
                  :key="index"
                  :label="item.name"
                  :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 保存按钮 -->
      <div class="button_box">
        <el-button class="primary_btn" @click="cancel" size="small">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click.stop="changeSortSave" size="small">{{$t('public.save')}}</el-button>
      </div>
    </el-form>
  </div>
</template>
<script type="text/javascript">
  // import bus from '@/store/eventBus'
  import draggable from 'vuedraggable'
  import { deepClone } from '@/utils/m7Utils'
  // import * as types from '@/store/modules/webchat/mutation-types.js'
  export default {
    name: 'webchatQuickReplyEdit',
    props: {
      // 分类或快捷回复的数据
      editDataProp: {
        type: Object,
        default: function () {
          return {
            data: []
          }
        }
      },
      // 当前快捷回复的分类的id
      currentCategoryId: {
        type: String,
        default: ''
      },
      // 当前快捷回复分类的名称
      currentCategoryName: {
        type: String,
        default: '无分类'
      },
      // 编辑的是快捷回复还是分类  'list'快捷回复  'sort'分类
      todoType: {
        type: String,
        default: 'list'
      },
      // 是否是变更分类操作
      changeSortFlag: {
        type: Boolean,
        default: false
      },
      // 编辑框添加按钮文案
      btnTitle: {
        type: String,
        default: '增加快捷语'
      },
      // 变更分类的时候的分类数据
      sort: {
        type: Array,
        default: [
          {
            _id: '',
            name: '无分类'
          }
        ]
      },
      // 随机数，用来每次点开的时候重置dialog
      random: {
        type: Number,
        default: 0
      },
      changeSortCategoryId: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        editData: {
          data: []
        },
        addData: [],
        editindex: -1,
        oldData: '',
        moveSort: {
          categoryId: '',
          checkedReply: []
        },
        isEdit: false,
        isAdd: false,
        textarea: {
          content: ''
        },
        sortRules: {
          categoryId: [
            { required: true, message: '请选择分类', trigger: 'change' }
          ],
          checkedReply: [
            { type: 'array', required: true, message: '请至少选择一快捷回复', trigger: 'change' }
          ]
        }
      }
    },
    watch: {
      random () {
        this.moveSort.categoryId = ''
        this.moveSort.checkedReply = []
        this.editindex = -1
        this.isEdit = false
        this.isAdd = false
        this.addData = []
        this.initEditData()
        if (this.changeSortFlag && this.$refs.moveSort) {
          this.$refs.moveSort.resetFields()
        }
      }
    },
    methods: {
      // 删除快捷回复或分类
      removeDomain (item) {
        var index = this.editData.data.indexOf(item)
        this.editData.data.splice(index, 1)
      },
      // 初始化数据
      initEditData () {
        let data = deepClone(this.editDataProp.data)
        if (this.todoType === 'sort' && data.length && !this.changeSortFlag) {
          data.forEach((item) => {
            this.$set(item, 'content', item.name)
          })
        }
        this.editData.data = data
      },
      // 添加快捷回复或分类
      addDomain () {
        if (this.isEdit) {
          return
        }
        this.isAdd = true
        this.addData.push({content: ''})
        this.$nextTick(function () {
          // this.scrollToBottom({scrollName: 'quick_replay_box', warpName: 'quickreplay_box'})
        })
      },
      // 保存并发送编辑的数组
      custQkReSubmit () {
        if (this.editindex !== -1 || this.addData.length) {
          if (this.todoType === 'list') {
            this.$message.error(this.$t('webchat.quickReplayNeedSave'))
          } else {
            this.$message.error(this.$t('webchat.quickReplaySortNeedSave'))
          }
          return
        }
        // 保存快捷回复
        let self = this
        if (self.todoType === 'list') {
          let dataOne = {
            quickreplys: self.editData.data,
            categoryId: self.changeSortCategoryId === 'all' ? '' : self.changeSortCategoryId,
            moduleType: 'webchat'
          }
          self.$store.dispatch('webchatSaveQuickReply', dataOne).then((res) => {
            if (res && res.success) {
              let dataTwo = {
                'moduleType': 'webchat',
                'categoryId': self.changeSortCategoryId === 'all' ? '' : self.changeSortCategoryId
              }
              self.$store.dispatch('getQuickReplyByCategory', dataTwo).then((res) => {
                console.log(res)
                let data = {
                  quickreplys: res.quickreplys,
                  categoryId: self.changeSortCategoryId
                }
                this.$emit('saveQuickReply', data)
              })
            }
          })
        } else if (self.todoType === 'sort') {
          // 保存分类
          let sortData = deepClone(self.editData.data)
          sortData.forEach((item) => {
            self.$set(item, 'name', item.content)
            delete item.content
          })
          let data = {
            categories: sortData,
            moduleType: 'webchat'
          }
          self.$store.dispatch('updateQuickReplyCategories', data).then((res) => {
            if (res && res.success) {
              this.$emit('queryQuickReplyCategories', {data: sortData})
            }
          })
        }
      },
      trim (data) {
        let _str = data
        return _str.replace(/(^\s*)|(\s*$)/g, '')
      },
      // 保存编辑数据
      saveEdit (data, todo, index) {
        if (todo === 'edit') {
          if (!this.textarea.content || !this.trim(this.textarea.content)) {
            this.$message.error(this.$t('webchat.quickReplayNotEmpty'))
            return
          }
          this.$set(data, 'content', this.trim(this.textarea.content))
          this.editindex = -1
          this.isEdit = false
          this.textarea.content = ''
        } else {
          if (!data.content || !this.trim(data.content)) {
            this.$message.error(this.$t('webchat.quickReplayNotEmpty'))
            return
          }
          this.$set(data, 'content', this.trim(data.content))
          this.editData.data.push(data)
          this.addData.splice(index, 1)
          if (!this.addData.length) {
            this.isAdd = false
          }
        }
      },
      // 取消编辑数据
      cancelEdit (obj, todo, index) {
        if (todo === 'edit') {
          this.$set(this.editData.data[this.editindex], 'content', deepClone(this.oldData))
          this.editindex = -1
          this.isEdit = false
          this.textarea.content = ''
        } else {
          this.addData.splice(index, 1)
          if (!this.addData.length) {
            this.isAdd = false
          }
        }
      },
      // 编辑数据
      changeEditIndex (data) {
        if (this.isAdd || this.isEdit) {
          return
        }
        this.isEdit = true
        this.oldData = deepClone(this.editData.data[data].content)
        this.editindex = data
        this.textarea.content = this.oldData
      },
      // 取消并退出dialog
      cancel () {
        this.$emit('cancel')
      },
      // 保存变更分类
      changeSortSave () {
        let self = this
        this.$refs['moveSort'].validate((valid) => {
          if (valid) {
            console.log(self.moveSort)
            let categoryId = self.moveSort.categoryId
            if (categoryId === 'all') {
              categoryId = ''
            }
            let data = {
              moduleType: 'webchat',
              idList: self.moveSort.checkedReply,
              categoryId: categoryId
            }
            self.$store.dispatch('changeCategoryOfQuickReplies', data).then((res) => {
              console.log(res)
              this.$emit('changeQuickReplySrt', {
                idList: self.moveSort.checkedReply,
                preCategoryId: this.changeSortCategoryId,
                nextCategoryId: categoryId || 'all'
              })
            })
          }
        })
      }
    },
    components: {
      draggable
    },
    beforeMount () {
      this.initEditData()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .quickreply_li
    margin-bottom 10px
    .span_btn
      position absolute
      right -2px
      top 50%
      margin-top -7px
      padding 2px 0
      cursor pointer
      font-size 12px
      color $c-pink
      user-select none
  .span_btn

  .button_box
    padding 10px 0
    text-align right
  .check_box_li
    display block
    margin 0
  .content_span
    width calc(100% - 50px)
    display inline-block
    user-select none
    vertical-align top
    margin-left 20px
    color #424242
    &:hover
      text-overflow unset
      white-space initial
      word-break break-all
  .todo_box
    display inline-block
    width 50px
    height 100%
    position absolute
    &:after
      content ""
      display inline-block
      width 0
      height 100%
      vertical-align middle
      overflow hidden
    span
      cursor pointer
      margin-left 8px
    .icon-xuanzhong
      color $c-main
    .icon-qiapianshangdeguanbi
      color $c-pink
  .title
    margin-bottom 10px
    color $c-prompt
  .add-btn
    margin-top 10px
  .add_box_textarea
    position relative
  .icon-shunxutuozhuai
    cursor move
    color $c-affix
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
</style>
